import os
import time
import re
import sys

LOG_FILE = os.path.join('%s%slogs' % (os.path.dirname(os.path.abspath(__file__)), os.sep),
                        'update_host_sw_%s.log' % time.strftime('%Y%m%d%H%M%S'))

from _log import FileLog
LOG = FileLog(LOG_FILE)

from _db_connection import DatabaseConnection

PSEXEC_DIR = '%s%sPsExec.exe' % (os.path.dirname(os.path.abspath(__file__), os.sep)

SUCCESS = 0

NA_COPY_IN_PROGRESS = 10
NA_COPY_FAIL = 11
NA_COPY_SUCCESS = 19

SART_COPY_IN_PROGRESS = 30
SART_COPY_FAIL = 31
SART_COPY_SUCCESS = 39

SART_INSTALL_IN_PROGRESS = 40
SART_INSTALL_FAIL = 41
SART_INSTALL_TIMEOUT = 42
SART_INSTALL_SUCCESS = 49


def _update_host_sw_version(host, na_build, sart_build, cms_build):
    LOG._log('INFO: start _update_host_sw_version %s' % host[0])

    if (na_build[0] != 'UNDEFINED'):
        _update_na(host, na_build)
    if (sart_build[0] != 'UNDEFINED'):
        _update_sart(host, sart_build)
    if (cms_build[0] != 'UNDEFINED'):
        _update_cms(host, cms_build)

    LOG._log('INFO: end _update_host_sw_version %s' % host_ip)


def _update_na(host, na_build):
    """
    Update host NA build
    """
    LOG._log('INFO: start _update_na %s' % host[0])

    copy_command = r'copy /Y %s \\%s\%s' % (na_build[1], host[0], host[5])
    LOG._log('INFO: copy command (%s)' % copy_command)

    _update_host_status(host[0], NA_COPY_IN_PROGRESS)

    if os.system(copy_command) != SUCCESS:
        LOG._log('ERROR: NA build %s copy to %s failed' % (na_build[1], host[0]))
        _update_host_status(host[0], NA_COPY_FAIL)
    else:
        _update_host_status(host[0], NA_COPY_SUCCESS)


    """
    install_command = r'PsExec.exe \\\\%s -u %s\\%s -p %s %s\\%s' % (host_ip, host_name, username, password, shared_path, build_file_name)
    LOG._log('INFO: install command %s' % install_command)

    #_update_host_status(host_ip, NA_INSTALL_IN_PROGRESS)
    if os.system(copy_command) != SUCCESS:
        LOG._log('ERROR: NA build %s install to %s failed' % (na_build_id, host_ip))
        #_update_host_status(host_ip, NA_INSTALL_FAIL)
    else:
        #_update_host_status(host_ip, NA_INSTALL_SUCCESS)
        pass
    """

    LOG._log('INFO: end _update_na %s' % host[0])

def _update_sart(host, sart_build):
    """
    Update host SART build
    """
    LOG._log('INFO: start _update_sart %s' % host[0])

    copy_command = r'copy /Y %s \\%s\%s' % (sart_build[1], host[0], host[5])
    LOG._log('INFO: copy command (%s)' % copy_command)

    _update_host_status(host[0], SART_COPY_IN_PROGRESS)

    if os.system(copy_command) != SUCCESS:
        LOG._log('ERROR: SART build %s copy to %s failed' % (sart_build[1], host[0]))
        _update_host_status(host[0], SART_COPY_FAIL)
    else:
        _update_host_status(host[0], SART_COPY_SUCCESS)


    install_command = r'%s \\%s -u %s\%s -p %s %s\%s' % (PSEXEC_DIR, host[0], host[1], host[2], host[3], host[4], sart_build[2])
    LOG._log('INFO: install command %s' % install_command)

    _update_host_status(host[0], SART_INSTALL_IN_PROGRESS)

    import subprocess, datetime, signal
    start = datetime.datetime.now()
    process = subprocess.Popen(install_command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    while process.poll() is None:
        time.sleep(1)
        now = datetime.datetime.now()
        if (now - start).seconds > 1:
            os.kill(process.pid, signal.SIGTERM)
            #os.waitpid(-1, os.WNOHANG)
            update_host_status(host[0], SART_INSTALL_TIMEOUT)
            return
    response = process.stdout.read()
    error = process.stderr.read()
    if error:
        LOG._log('ERROR: install SART failed, error msg is (%s)' % error)
        _update_host_status(host[0], SART_INSTALL_FAIL)
    else:
        LOG._log('INFO: response (%s)' % response)
        _update_host_status(host[0], SART_INSTALL_SUCCESS)

    """
    if os.system('echo ') != SUCCESS:
        LOG._log('ERROR: SART build %s install to %s failed' % (sart_build[1], host[0]))
        _update_host_status(host[0], SART_INSTALL_FAIL)
    else:
        _update_host_status(host[0], SART_INSTALL_SUCCESS)
"""
    LOG._log('INFO: end _update_sart %s' % host[0])


def _update_host_status(host_ip, status):
    LOG._log('INFO: start _update_host_status %s:%s' % (host_ip, status))

    sql_command = 'update host set status=%s where host_ip="%s"' % (status, host_ip)
    DB_CONN.execute_sql_statement(sql_command)

    LOG._log('INFO: end _update_host_status %s:%s' % (host_ip, status))



if __name__ == '__main__':
    if len(sys.argv) != 16:
        LOG._log('ERROR: calling script error with wrong argument number %s' % len(sys.argv))
        LOG._log('INFO: %s' % ','.join(arg for arg in sys.argv))
        exit(1)

    host_ip = sys.argv[1]
    host_name = sys.argv[2]
    host_username = sys.argv[3]
    host_password = sys.argv[4]
    host_shared_path = sys.argv[5]
    host_shared_name = sys.argv[6]
    host = (host_ip, host_name, host_username, host_password, host_shared_path, host_shared_name)

    na_build_id = sys.argv[7]
    na_build_path = sys.argv[8]
    na_build_file_name = sys.argv[9]
    na_build = (na_build_id, na_build_path, na_build_file_name)

    sart_build_id = sys.argv[10]
    sart_build_path = sys.argv[11]
    sart_build_file_name = sys.argv[12]
    sart_build = (sart_build_id, sart_build_path, sart_build_file_name)

    cms_build_id = sys.argv[13]
    cms_build_path = sys.argv[14]
    cms_build_file_name = sys.argv[15]
    cms_build = (cms_build_id, cms_build_path, cms_build_file_name)

    DB_CONN = DatabaseConnection(LOG)
    try:
		_update_host_sw_version(host, na_build, sart_build, cms_build)
    except Exception, e:
        LOG._log("ERROR: %s" % e)
        pass
    finally:
	    DB_CONN.close_database_connection()